<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />



  <meta name="google-site-verification" content="googlead9dc5c68da2c41a" />








  <meta name="baidu-site-verification" content="baV2kbPkNW" />







  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico?v=5.1.4" color="#222">





  <meta name="keywords" content="机器学习,林轩田,基石,笔记," />





  <link rel="alternate" href="/atom.xml" title="红色石头的机器学习之路" type="application/atom+xml" />






<meta name="keywords" content="机器学习,林轩田,基石,笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="台湾大学林轩田机器学习基石课程学习笔记15 -- Validation">
<meta property="og:url" content="https://redstonewill.github.io/2018/03/17/15/index.html">
<meta property="og:site_name" content="红色石头的机器学习之路">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://img.blog.csdn.net/20170601204900309?imageView/2/w/500/q/100">
<meta property="og:image" content="http://img.blog.csdn.net/20170601204900309?">
<meta property="og:image" content="http://img.blog.csdn.net/20170601213602033?">
<meta property="og:image" content="http://img.blog.csdn.net/20170601214722299?">
<meta property="og:image" content="http://img.blog.csdn.net/20170601231504059?">
<meta property="og:image" content="http://img.blog.csdn.net/20170601233528299?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602080623574?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602082146642?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602083650808?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602085825099?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602090711596?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602104358868?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602143003909?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602143613402?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602150552663?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602154420527?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602154609826?">
<meta property="og:image" content="http://img.blog.csdn.net/20170602155243060?">
<meta property="og:updated_time" content="2018-03-17T14:19:31.276Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="台湾大学林轩田机器学习基石课程学习笔记15 -- Validation">
<meta name="twitter:image" content="http://img.blog.csdn.net/20170601204900309?imageView/2/w/500/q/100">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'ZFJHIGA2DV',
      apiKey: 'e3baeea7f059baffe169cc0eec8adacf',
      indexName: 'redstonewillblog',
      hits: {"per_page":10},
      labels: {"input_placeholder":"输入关键词进行搜索","hits_empty":"找不到关于 ${query} 的文章","hits_stats":"共找到 ${hits} 篇文章，耗时${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://redstonewill.github.io/2018/03/17/15/"/>





  <title>台湾大学林轩田机器学习基石课程学习笔记15 -- Validation | 红色石头的机器学习之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/RedstoneWill" class="github-corner" aria-label="View source on Github"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>
	
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">红色石头的机器学习之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">公众号ID：redstonewill</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://redstonewill.github.io/2018/03/17/15/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="红色石头">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/blog-logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="红色石头的机器学习之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">台湾大学林轩田机器学习基石课程学习笔记15 -- Validation</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-17T21:58:47+08:00">
                2018-03-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/机器学习/林轩田机器学习基石/" itemprop="url" rel="index">
                    <span itemprop="name">林轩田机器学习基石</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/03/17/15/" class="leancloud_visitors" data-flag-title="台湾大学林轩田机器学习基石课程学习笔记15 -- Validation">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,600
                </span>
              

              

              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p><img src="http://img.blog.csdn.net/20170601204900309?imageView/2/w/500/q/100" alt="这里写图片描述"><br><a id="more"></a></p>
<blockquote>
<p>我的CSDN博客地址：<a href="http://blog.csdn.net/red_stone1" target="_blank" rel="noopener">红色石头的专栏</a><br>我的知乎主页：<a href="https://www.zhihu.com/people/red_stone_wl" target="_blank" rel="noopener">红色石头</a><br>我的微博：<a href="https://weibo.com/6479023696/profile?topnav=1&amp;wvr=6&amp;is_all=1" target="_blank" rel="noopener">RedstoneWill的微博</a><br>我的GitHub：<a href="https://github.com/RedstoneWill" target="_blank" rel="noopener">RedstoneWill的GitHub</a><br>我的微信公众号：红色石头的机器学习之路（ID：redstonewill）<br>欢迎大家关注我！共同学习，共同进步！</p>
</blockquote>
<p>上节课我们主要讲了为了避免overfitting，可以使用regularization方法来解决。在之前的$E_{in}$上加上一个regularizer，生成$E_{aug}$，将其最小化，这样可以有效减少模型的复杂度，避免过拟合现象的发生。那么，机器学习领域还有许多选择，如何保证训练的模型具有良好的泛化能力？本节课将介绍一些概念和方法来解决这个选择性的问题。</p>
<h3 id="Model-Selection-Problem"><a href="#Model-Selection-Problem" class="headerlink" title="Model Selection Problem"></a>Model Selection Problem</h3><p>机器学习模型建立的过程中有许多选择，例如对于简单的二元分类问题，首先是算法A的选择，有PLA，pocket，linear regression，logistic regression等等；其次是迭代次数T的选择，有100，1000,10000等等；之后是学习速率$\eta$的选择，有1，0.01,0.0001等等；接着是模型特征转换$\Phi$的选择，有linear，quadratic，poly-10，Legendre-poly-10等等；然后是正则化regularizer的选择，有L2，L1等等；最后是正则化系数$\lambda$的选择，有0，0.01，1等等。不同的选择搭配，有不同的机器学习效果。我们的目标就是找到最合适的选择搭配，得到一个好的矩g，构建最佳的机器学习模型。</p>
<p><img src="http://img.blog.csdn.net/20170601204900309?" alt="这里写图片描述"></p>
<p>假设有M个模型，对应有$H_1,H_2,\cdots,H_M$，即有M个hypothesis set，演算法为$A_1,A_2,\cdots,A_M$，共M个。我们的目标是从这M个hypothesis set中选择一个模型$H_{m^*}$，通过演算法$A_{m^*}$对样本集D的训练，得到一个最好的矩$g_{m^*}$，使其$E_{out}(g_{m^*})$最小。所以，问题的关键就是机器学习中如何选择到最好的矩$g_{m^*}$。</p>
<p>考虑有这样一种方法，对M个模型分别计算使$E_{in}$最小的矩g，再横向比较，取其中能使$E_{in}$最小的模型的矩$g_{m^*}$：</p>
<p><img src="http://img.blog.csdn.net/20170601213602033?" alt="这里写图片描述"></p>
<p>但是$E_{in}$足够小并不能表示模型好，反而可能表示训练的矩$g_{m^*}$发生了过拟合，泛化能力很差。而且这种“模型选择+学习训练”的过程，它的VC Dimension是$d_{VC}(H_1\cup H_2)$，模型复杂度增加。总的来说，泛化能力差，用$E_{in}$来选择模型是不好的。</p>
<p>另外一种方法，如果有这样一个独立于训练样本的测试集，将M个模型在测试集上进行测试，看一下$E_{test}$的大小，则选取$E_{test}$最小的模型作为最佳模型：</p>
<p><img src="http://img.blog.csdn.net/20170601214722299?" alt="这里写图片描述"></p>
<p>这种测试集验证的方法，根据finite-bin Hoffding不等式，可以得到：</p>
<p>$$E_{out}(g_{m^*})\leq E_{test}(g_{m^*})+O(\sqrt \frac{log M}{N_{test}})$$</p>
<p>由上式可以看出，模型个数M越少，测试集数目越大，那么$O(\sqrt \frac{log M}{N_{test}})$越小，即$E_{test}(g_{m^*})$越接近于$E_{out}(g_{m^*})$。</p>
<p>下面比较一下之前讲的两种方法，第一种方法使用$E_{in}$作为判断基准，使用的数据集就是训练集D本身；第二种方法使用$E_{test}$作为判断基准，使用的是独立于训练集D之外的测试集。前者不仅使用D来训练不同的$g_m$，而且又使用D来选择最好的$g_{m^*}$，那么$g_{m^*}$对未知数据并不一定泛化能力好。举个例子，这相当于老师用学生做过的练习题再来对学生进行考试，那么即使学生得到高分，也不能说明他的学习能力强。所以最小化$E_{in}$的方法并不科学。而后者使用的是独立于D的测试集，相当于新的考试题能更好地反映学生的真实水平，所以最小化$E_{test}$更加理想。</p>
<p><img src="http://img.blog.csdn.net/20170601231504059?" alt="这里写图片描述"></p>
<p>但是，我们拿到的一都是训练集D，测试集是拿不到的。所以，寻找一种折中的办法，我们可以使用已有的训练集D来创造一个验证集validation set，即从D中划出一部分$D_{val}$作为验证集。D另外的部分作为训练模型使用，$D_{val}$独立开来，用来测试各个模型的好坏，最小化$E_{val}$，从而选择最佳的$g_{m^*}$。</p>
<p><img src="http://img.blog.csdn.net/20170601233528299?" alt="这里写图片描述"></p>
<h3 id="Validation"><a href="#Validation" class="headerlink" title="Validation"></a>Validation</h3><p>从训练集D中抽出一部分K个数据作为验证集$D_{val}$，$D_{val}$对应的error记为$E_{val}$。这样做的一个前提是保证$D_{val}$独立同分布（iid）于P(x,y)，也就是说$D_{val}$的选择是从D中平均随机抽样得到的，这样能够把$E_{val}$与$E_{out}$联系起来。D中去除$D_{val}$后的数据就是供模型选择的训练数据$D_{train}$，其大小为N-k。从$D_{train}$中选择最好的矩，记为$g_m^-$。</p>
<p><img src="http://img.blog.csdn.net/20170602080623574?" alt="这里写图片描述"></p>
<p>假如D共有1000个样本，那么可以选择其中900个$D_{train}$，剩下的100个作为$D_{val}$。使用$D_{train}$训练模型，得到最佳的$g_m^-$，使用$g_m^-$对$D_{val}$进行验证，得到如下Hoffding不等式：</p>
<p>$$E_{out}(g_m^-)\leq E_{val}(g_m^-)+O(\sqrt \frac{log M}{K})$$</p>
<p>假设有M种模型hypothesis set，$D_{val}$的数量为K，那么从每种模型m中得到一个在$D_{val}$上表现最好的矩，再横向比较，从M个矩中选择一个最好的$m^*$作为我们最终得到的模型。</p>
<p><img src="http://img.blog.csdn.net/20170602082146642?" alt="这里写图片描述"></p>
<p>现在由于数量为N的总样本D的一部分K作为验证集，那么只有N-k个样本可供训练。从$D_{train}$中得到最好的$g_{m^*}^-$，而总样本D对应的最好的矩为$g_{m^*}$。根据之前的leraning curve很容易知道，训练样本越多，得到的模型越准确，其hypothesis越接近target function，即D的$E_{out}$比$D_{train}$的$E_{out}$要小：</p>
<p><img src="http://img.blog.csdn.net/20170602083650808?" alt="这里写图片描述"></p>
<p>所以，我们通常的做法是通过$D_{val}$来选择最好的矩$g_{m^*}^-$对应的模型$m^*$，再对整体样本集D使用该模型进行训练，最终得到最好的矩$g_{m^*}$。</p>
<p>总结一下，使用验证集进行模型选择的整个过程为：先将D分成两个部分，一个是训练样本$D_{train}$，一个是验证集$D_{val}$。若有M个模型，那么分别对每个模型在$D_{train}$上进行训练，得到矩$g_{m}^-$，再用$D_{val}$对每个$g_{m}^-$进行验证，选择表现最好的矩$g_{m^*}^-$，则该矩对应的模型被选择。最后使用该模型对整个D进行训练，得到最终的$g_{m^*}$。下图展示了整个模型选择的过程：</p>
<p><img src="http://img.blog.csdn.net/20170602085825099?" alt="这里写图片描述"></p>
<p>不等式关系满足：</p>
<p>$$E_{out}(g_{m^*})\leq E_{out}(g_{m^*}^-)\leq E_{val}(g_{m^*}^-)+O(\sqrt \frac{log M}{K})$$</p>
<p>下面我们举个例子来解释这种模型选择的方法的优越性，假设有两个模型：一个是5阶多项式$H_{\Phi_5}$，一个是10阶多项式$H_{\Phi_{10}}$。通过不使用验证集和使用验证集两种方法对模型选择结果进行比较，分析结果如下：</p>
<p><img src="http://img.blog.csdn.net/20170602090711596?" alt="这里写图片描述"></p>
<p>图中，横坐标表示验证集数量K，纵坐标表示$E_{out}$大小。黑色水平线表示没有验证集，完全使用$E_{in}$进行判断基准，那么$H_{\Phi_{10}}$更好一些，但是这种方法的$E_{out}$比较大，而且与K无关。黑色虚线表示测试集非常接近实际数据，这是一种理想的情况，其$E_{out}$很小，同样也与K无关，实际中很难得到这条虚线。红色曲线表示使用验证集，但是最终选取的矩是$g_{m^*}^-$，其趋势是随着K的增加，它对应的$E_{out}$先减小再增大，当K大于一定值的时候，甚至会超过黑色水平线。蓝色曲线表示也使用验证集，最终选取的矩是$g_{m^*}$，其趋势是随着K的增加，它对应的$E_{out}$先缓慢减小再缓慢增大，且一直位于红色曲线和黑色直线之下。从此可见，蓝色曲线对应的方法最好，符合我们之前讨论的使用验证集进行模型选择效果最好。</p>
<p>这里提一点，当K大于一定的值时，红色曲线会超过黑色直线。这是因为随着K的增大，$D_{val}$增大，但可供模型训练的$D_{train}$在减小，那得到的$g_{m^*}^-$不具有很好的泛化能力，即对应的$E_{out}$会增大，甚至当K增大到一定值时，比$E_{in}$模型更差。</p>
<p>那么，如何设置验证集K值的大小呢？根据之前的分析：</p>
<p><img src="http://img.blog.csdn.net/20170602104358868?" alt="这里写图片描述"></p>
<p>当K值很大时，$E_{val}\approx E_{out}$，但是$g_m^-$与$g_m$相差很大；当K值很小是，$g_m^-\approx g_m$，但是$E_{val}$与$E_{out}$可能相差很大。所以有个折中的办法，通常设置$k=\frac N5$。值得一提的是，划分验证集，通常并不会增加整体时间复杂度，反而会减少，因为$D_{train}$减少了。</p>
<h3 id="Leave-One-Out-Cross-Validation"><a href="#Leave-One-Out-Cross-Validation" class="headerlink" title="Leave-One-Out Cross Validation"></a>Leave-One-Out Cross Validation</h3><p>假如考虑一个极端的例子，k=1，也就是说验证集大小为1，即每次只用一组数据对$g_m$进行验证。这样做的优点是$g_m^-\approx g_m$，但是$E_{val}$与$E_{out}$可能相差很大。为了避免$E_{val}$与$E_{out}$相差很大，每次从D中取一组作为验证集，直到所有样本都作过验证集，共计算N次，最后对验证误差求平均，得到$E_{loocv}(H,A)$，这种方法称之为留一法交叉验证，表达式为：</p>
<p>$$E_{loocv}(H,A)=\frac1N\sum_{n=1}^Ne_n=\frac1N\sum_{n=1}^Nerr(g_n^-(x_n),y_n)$$</p>
<p>这样求平均的目的是为了让$E_{loocv}(H,A)$尽可能地接近$E_{out}(g)$。</p>
<p>下面用一个例子图解留一法的过程：</p>
<p><img src="http://img.blog.csdn.net/20170602143003909?" alt="这里写图片描述"></p>
<p>如上图所示，要对二维平面上的三个点做拟合，上面三个图表示的是线性模型，下面三个图表示的是常数模型。对于两种模型，分别使用留一交叉验证法来计算$E_{loocv}$，计算过程都是每次将一个点作为验证集，其他两个点作为训练集，最终将得到的验证误差求平均值，就得到了$E_{loocv}(linear)$和$E_{loocv}(constant)$，比较两个值的大小，取值小对应的模型即为最佳模型。</p>
<p><img src="http://img.blog.csdn.net/20170602143613402?" alt="这里写图片描述"></p>
<p>接下来，我们从理论上分析Leave-One-Out方法的可行性，即$E_{loocv}(H,A)$是否能保证$E_{out}$的矩足够好？假设有不同的数据集D，它的期望分布记为$\varepsilon_D$，则其$E_{loocv}(H,A)$可以通过推导，等于$E_{out}(N-1)$的平均值。由于N-1近似为N，$E_{out}(N-1)$的平均值也近似等于$E_{out}(N)$的平均值。具体推导过程如下：</p>
<p><img src="http://img.blog.csdn.net/20170602150552663?" alt="这里写图片描述"></p>
<p>最终我们得到的结论是$E_{loocv}(H,A)$的期望值和$E_{out}(g^-)$的期望值是相近的，这代表得到了比较理想的$E_{out}(g)$，Leave-One-Out方法是可行的。</p>
<p>举一个例子，使用两个特征：Average Intensity和Symmetry加上这两个特征的非线性变换（例如高阶项）来进行手写数字识别。平面特征分布如下图所示：</p>
<p><img src="http://img.blog.csdn.net/20170602154420527?" alt="这里写图片描述"></p>
<p>Error与特征数量的关系如下图所示：</p>
<p><img src="http://img.blog.csdn.net/20170602154609826?" alt="这里写图片描述"></p>
<p>从图中我们看出，随着特征数量的增加，$E_{in}$不断减小，$E_{out}$先减小再增大，虽然$E_{in}$是不断减小的，但是它与$E_{out}$的差距越来越大，发生了过拟合，泛化能力太差。而$E_{cv}$与$E_{out}$的分布基本一致，能较好地反映$E_{out}$的变化。所以，我们只要使用Leave-One-Out方法得到使$E_{cv}$最小的模型，就能保证其$E_{out}$足够小。下图是分别使用$E_{in}$和$E_{out}$进行训练得到的分类曲线：</p>
<p><img src="http://img.blog.csdn.net/20170602155243060?" alt="这里写图片描述"></p>
<p>很明显可以看出，使用$E_{in}$发生了过拟合，而$E_{loocv}$分类效果更好，泛化能力强。</p>
<h3 id="V-Fold-Cross-Validation"><a href="#V-Fold-Cross-Validation" class="headerlink" title="V-Fold Cross Validation"></a>V-Fold Cross Validation</h3><p>接下来我们看看Leave-One-Out可能的问题是什么。首先，第一个问题是计算量，假设N=1000，那么就需要计算1000次的$E_{loocv}$，再计算其平均值。当N很大的时候，计算量是巨大的，很耗费时间。第二个问题是稳定性，例如对于二分类问题，取值只有0和1两种，预测本身存在不稳定的因素，那么对所有的$E_{loocv}$计算平均值可能会带来很大的数值跳动，稳定性不好。所以，这两个因素决定了Leave-One-Out方法在实际中并不常用。</p>
<p>针对Leave-One-Out的缺点，我们对其作出了改进。Leave-One-Out是将N个数据分成N分，那么改进措施是将N个数据分成V份（例如V=10），计算过程与Leave-One-Out相似。这样可以减少总的计算量，又能进行交叉验证，得到最好的矩，这种方法称为V-折交叉验证。其实Leave-One-Out就是V-折交叉验证的一个极端例子。</p>
<p>$$E_{cv}(H,A)=\frac1V\sum_{v=1}^VE_{val}^{(V)}(g_V^-)$$</p>
<p>所以呢，一般的Validation使用V-折交叉验证来选择最佳的模型。值得一提的是Validation的数据来源也是样本集中的，所以并不能保证交叉验证的效果好，它的模型一定好。只有样本数据越多，越广泛，那么Validation的结果越可信，其选择的模型泛化能力越强。</p>
<h3 id="Summary"><a href="#Summary" class="headerlink" title="Summary"></a>Summary</h3><p>本节课主要介绍了Validation验证。先从如何选择一个好的模型开始切入，例如使用$E_{in}$、$E_{test}$都是不太好的，最终使用$E_{val}$来进行模型选择。然后详细介绍了Validation的过程。最后，介绍了Leave-One-Out和V-Fold Cross两种验证方法，比较它们各自的优点和缺点，实际情况下，V-Fold Cross更加常用。</p>
<p><strong><em>注明：</em></strong><br>文章中所有的图片均来自台湾大学林轩田《机器学习基石》课程</p>

      
    </div>
    
    
    
	
    
      <div>
        <div id="wechat_subscriber" style="display: block; padding: 10px 0; margin: 20px auto; width: 100%; text-align: center">
    <img id="wechat_subscriber_qcode" src="/uploads/wechat-qcode.jpg" alt="红色石头 wechat" style="width: 200px; max-width: 100%;"/>
    <div>欢迎您扫一扫上面的微信公众号，了解更多AI资源！</div>
</div>

      </div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="红色石头 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="红色石头 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    红色石头
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://redstonewill.github.io/2018/03/17/15/" title="台湾大学林轩田机器学习基石课程学习笔记15 -- Validation">https://redstonewill.github.io/2018/03/17/15/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/机器学习/" rel="tag"><i class="fa fa-tag"></i> 机器学习</a>
          
            <a href="/tags/林轩田/" rel="tag"><i class="fa fa-tag"></i> 林轩田</a>
          
            <a href="/tags/基石/" rel="tag"><i class="fa fa-tag"></i> 基石</a>
          
            <a href="/tags/笔记/" rel="tag"><i class="fa fa-tag"></i> 笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/03/17/14/" rel="next" title="台湾大学林轩田机器学习基石课程学习笔记14 -- Regularization">
                <i class="fa fa-chevron-left"></i> 台湾大学林轩田机器学习基石课程学习笔记14 -- Regularization
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/17/16/" rel="prev" title="台湾大学林轩田机器学习基石课程学习笔记16（完结） -- Three Learning Principles">
                台湾大学林轩田机器学习基石课程学习笔记16（完结） -- Three Learning Principles <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- Go to www.addthis.com/dashboard to customize your tools -->
<div class="addthis_inline_share_toolbox">
  <script type = "text/javascript" src = "//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-5aaa217593e0eff1" async = "async" ></script>
</div>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNDg0MS8xMTM3OA=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/blog-logo.jpg"
                alt="红色石头" />
            
              <p class="site-author-name" itemprop="name">红色石头</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/RedstoneWill" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://blog.csdn.net/red_stone1" target="_blank" title="CSDN">
                      
                        <i class="fa fa-fw fa-contao"></i>CSDN</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/red_stone_wl/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-globe"></i>知乎</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/redstonewill" target="_blank" title="微博">
                      
                        <i class="fa fa-fw fa-weibo"></i>微博</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:redstonewill@hotmail.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#Model-Selection-Problem"><span class="nav-number">1.</span> <span class="nav-text">Model Selection Problem</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Validation"><span class="nav-number">2.</span> <span class="nav-text">Validation</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Leave-One-Out-Cross-Validation"><span class="nav-number">3.</span> <span class="nav-text">Leave-One-Out Cross Validation</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#V-Fold-Cross-Validation"><span class="nav-number">4.</span> <span class="nav-text">V-Fold Cross Validation</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Summary"><span class="nav-number">5.</span> <span class="nav-text">Summary</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">红色石头</span>

  
</div>

<div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_pv"></span>
</span>
</div>









<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共150.1k字</span>
</div>
        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.4"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("GPinP9RLLAEN4cQw3GyGH1i6-gzGzoHsz", "P23pTYCEXWROAMFxuaSGYGIa");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
